using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class app_frame_loadTips : System.Web.UI.Page
{

    bool isForCompanyadmin = false;
    string Tomailid = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        //for (int i = 0; i < 1000000000; i++)
        //{
        //}
        setPageTitle();
        if (Request.QueryString.Count > 0)
        {
            if (Request.QueryString["fb"] != null)
            {
                if(Request.QueryString["IsMail"]!=null)
                {
                    if(Request.QueryString["IsMail"].ToString()!="")
                    {
                        isForCompanyadmin = Convert.ToBoolean(Request.QueryString["IsMail"].ToString());
                    }
                }

                if(Request.QueryString["EMid"]!=null)
                {
                    if(Request.QueryString["EMid"].ToString()!="")
                    {
                        Tomailid = Request.QueryString["EMid"].ToString();
                    }
                }
                    

                //Response.Write("Success");
                Response.Write(handleFeedBackRequest());
                return;
            }
        }
        if (Request.QueryString.Count > 0)
        {
            if (Request.QueryString["rp"] != null)
            {
                //Response.Write("success");
                Response.Write(handleResetPassword());
                return;
            }
        }
        if (Request.QueryString.Count < 2)//checks for only random number query string
        {
            if (Request.QueryString["rnd"] != null)
            {
                string fName = HttpContext.Current.Server.MapPath("") + @"\Tips.txt";
                if (File.Exists(fName))
                {
                    StreamReader sr = new StreamReader(fName);
                    ArrayList al = new ArrayList();
                    string temp = "";
                    while (!sr.EndOfStream)
                    {
                        temp = sr.ReadLine();
                        if (temp.Trim().Length > 0)
                            al.Add(temp);
                    }
                    sr.Close(); sr = null;
                    Response.Write(al[getRandomNumber(0, al.Count - 1)].ToString());
                }
                else
                    Response.Write("");
            }
            if (Request.QueryString["ses"] != null)
            {
                if (Session["userid"] == null)
                    Response.Write("Logout.aspx?EX=0");// Response.Write("Logout.aspx?LG=default.aspx&EX=0");//commented by Sampath for session expiry on 07-Jan-2011
                else
                    Response.Write("validsession");
            }
        }
        else
        {
            if (Request.QueryString["panelMode"] != null)
            {
                if (Request.QueryString["panelMode"].ToString() == "-1")
                    Session["collapsed"] = "false";
                else
                    Session["collapsed"] = "true";
            }
        }

        if (Request.QueryString["PB"] != null) // Control Paramter Bind lookup for Report Designer and dashboard
        {
            if (Request.QueryString["bnd"] != null)
                if (Request.QueryString["SD"] != null)
                {
                    Response.Write(GetParamterBindValue(Request.QueryString["bnd"].ToString(), Request.QueryString["SD"].ToString()));
                }
            return;
        }
    }
    private string handleResetPassword()
    {
        if (Session["servercon"] == null) return "Unable to Process.";
        if (Session["servercon"].ToString().Length<1) return "Unable to Process.";
        HDDatabase hdd = new HDDatabase();
        security sc = new security();
        string ret="";
        try
        {
            string userRowID = Request.QueryString["id"].ToString();
            string password = Request.QueryString["rp"].ToString();
            string err = string.Empty;
            if (!sc.validatePasswordLength(password, ref err)) // Added by 'Imran Gani' on 25-Nov-2013.
                return err;
            if (!sc.validatePasswordReuseCycle(password, ref err)) // Added by 'Imran Gani' on 25-Nov-2013.
                return err;
            password = security.encrypt(password);
            string sql = ""; int returned = -1; string userId = "";
            DataTable dt = hdd.GetDataTable("select * from sy_usr where af_row_id='" + userRowID + "'");

            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows.Count==1)
                    {
                    userId = dt.Rows[0]["user_id"].ToString();
                    sql = "update sy_usr set password='" + password + "' where af_row_id='" + userRowID + "'";
                    returned = hdd.ExecuteCmdObj(new System.Data.SqlClient.SqlCommand(sql));
                    if (returned > 0)
                    {
                        AuditLog AL = new AuditLog(); // Added by 'Imran Gani' on 25-Nov-2013.
                        AL.WritePasswordSecurityLog(Session["user_afrowid"].ToString(), userRowID, password, "reset password");
                        AL = null;
                        hdd = new HDDatabase(Session["servercon"].ToString());
                        sql = "update ngcompanyuser set password = '" + password + "' where company_id='" + HttpContext.Current.Session["company_id"].ToString().Replace("'", "''") + "' and user_id='" + userId.Replace("'", "''") + "'";
                        returned = hdd.ExecuteCmdObj(new System.Data.SqlClient.SqlCommand(sql));
                        if (returned > 0)
                            ret = "success";
                    }
                    else
                        ret = "Unable to Process.";
                    }
                    else
                        ret = "Multiple Users.";
                }
                else
                    ret = "User not found.";
            }
        }
        catch (Exception e)
        {
            ret = "Unable to Process";
        }
        finally
        {
            hdd = null;
            sc = null;
        }
        return ret;
    }
    private string handleFeedBackRequest()
    {
        //return "Unable to Submit";
        try
        {
            HDDatabase hdd = new HDDatabase();
            DataTable dt = hdd.GetDataTable("select * from sy_acr_mem where acr_id='48e3dc27301a23e9'");
            hdd = null;
            bool storeInDB = false; bool storedInDB = false;
            bool sendEMail = false; bool doneEmail = false; bool isEmailBased=false;
            bool feedbackSuccess = false;
            DataRow[] drSelect = new DataRow[] { };
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    drSelect = dt.Select("af_row_id='a8d1b6c65b471735'");
                    if (drSelect.Length > 0)
                    {
                        if (drSelect[0]["mem_value1"].ToString() == "true" || drSelect[0]["mem_value1"].ToString() == "1")
                            storeInDB = true;
                    }

                    drSelect = dt.Select("af_row_id = 'fb2a35dfafaf1323'");
                    if (drSelect.Length > 0)
                    {
                        if (drSelect[0]["mem_value1"].ToString().ToLower() == "true" || drSelect[0]["mem_value1"].ToString() == "1")
                        {
                            isEmailBased = true;
                        }
                    }
                    drSelect = dt.Select("af_row_id='b13034b44961ff77'");
                    if (drSelect.Length > 0)
                    {
                        if (drSelect[0]["mem_value1"].ToString() == "true" || drSelect[0]["mem_value1"].ToString() == "1")
                            sendEMail = true;
                    }
                    
                    if (storeInDB)
                        storedInDB = storeFeedBackinDB();
                    if (sendEMail)
                        // doneEmail = sendFeedbackEmail(drSelect[0]["mem_value2"].ToString());
                        doneEmail = sendFeedbackEmail(drSelect[0]["mem_value2"].ToString(), isEmailBased);
                    feedbackSuccess = (storeInDB && storedInDB) || (sendEMail && doneEmail);
                    return feedbackSuccess == true ? "success" : "Unable to submit";
                }
                else
                    return "Invalid Settings";
            }
            else
                return "Invalid Settings";
        }
        catch(Exception e)
        {
            return "Unable to Process";
        }
    }
    private bool sendFeedbackEmail(string toEmail)
    {
        //return false;
        if (toEmail.Trim().Length<1) return false;
        bool ret = false;
        //string fromEmail = toEmail;
        //bool isEmailBased = isBasedOnEmail();
        //string strtomailid =GetFromAddress(isEmailBased);

        //if (strtomailid.Trim() != "")
        //{
        //    fromEmail = strtomailid;
        //}

        CommonFunctions cf = new CommonFunctions();
        ret = cf.sendMail(toEmail, toEmail, true, getFeedBackContent(), "Feedback from User") == "success";
        cf = null;
        return ret;
    }
    private bool sendFeedbackEmail(string toEmail,bool isEmailBased)
    {
        //return false;
        if (toEmail.Trim().Length < 1) return false;
        bool ret = false;
                  
        string fromEmail = toEmail;
        //bool isEmailBased = isBasedOnEmail();
        string strfrommailid = GetFromAddress(isEmailBased);

        if (strfrommailid.Trim() != "")
        {
            fromEmail = strfrommailid;
        }

        if (Tomailid != "")
        {
            toEmail = Tomailid;
        }

        CommonFunctions cf = new CommonFunctions();
        if (isForCompanyadmin)
        {
            ret = cf.sendMail(toEmail, fromEmail, true, getFeedBackContentForCompanyAdmins(), "Feedback from User") == "success";
        }
        else
        {

            ret = cf.sendMail(toEmail, fromEmail, true, getFeedBackContent(), "Feedback from User") == "success";
        }
        cf = null;
        return ret;
    }
    private string getFeedBackContent()
    {
        ////string ret = "<font face='Arial' size='2px'>" + "<b>Feedback</b>:<br>" + Server.UrlDecode(Request.QueryString["fb"].ToString()) + "" +
        ////                "<br><br><b>Page</b>: " + Request.UrlReferrer.ToString() +
        ////                (Session["user_name"] == null ? "" : ("<br><br><b>User</b>: " + Session["user_name"].ToString())) +
        ////                (Session["company_id"] == null ? "" : ("<br><br><b>Company</b>: " + Session["company_id"].ToString())) +
        ////                "<br><br>-- This is a system generated email." + "</font>";

        string companyname = Session["company_afrowid"] == null ? "" : GetCompanyName(Session["company_afrowid"].ToString())+"&nbsp; ("+Session["company_id"].ToString()+")";
        string ret = "<font face='Arial' size='2px'>" + "<b>Feedback</b>:<br>" + Server.UrlDecode(Request.QueryString["fb"].ToString()) + "" +
                        "<br><br><b>Page</b>: " + Request.UrlReferrer.ToString() +
                        (Session["user_name"] == null ? "" : ("<br><br><b>User</b>: " + Session["user_name"].ToString())) +
                        (Session["company_id"] == null ? "" : ("<br><br><b>Company</b>: " + companyname )) +
                        "<br><br>-- This is a system generated email." + "</font>";
        return ret;
    }

    private string getFeedBackContentForCompanyAdmins()
    {
        string companyname = Session["company_afrowid"] == null ? "" : GetCompanyName(Session["company_afrowid"].ToString())+"";
        string ret = "<font face='Arial' size='2px'>" + "<b>Feedback</b>:<br>" + Server.UrlDecode(Request.QueryString["fb"].ToString()) + "" +
                        "<br><br>"+//<b>Page</b>: " + Request.UrlReferrer.ToString() +
                        (Session["user_name"] == null ? "" : ("<br><br><b>User</b>: " + Session["user_name"].ToString())) +
                        (Session["company_id"] == null ? "" : ("<br><br><b>Company</b>: " + companyname )) +
                        "</font>";
        return ret;
    }
    private bool storeFeedBackinDB()
    {
        bool ret = false;
        HDDatabase hddAD = new HDDatabase(Session["servercon"].ToString());
        string sql = "insert into sy_page_feedback(feedback,page,userid,companyid,created_at) values('" +
                    Server.UrlDecode(Request.QueryString["fb"].ToString()) + "','" + Request.UrlReferrer.ToString() + "','" + 
                    (Session["user_name"] == null ? "" : Session["user_name"].ToString()) + "','" + 
                    (Session["company_id"] == null ? "" : Session["company_id"].ToString()) + "','" + 
                    DateTime.Now.ToUniversalTime().ToString(System.Globalization.CultureInfo.InvariantCulture) + "')";
        ret = hddAD.ExecuteCmdObj(new System.Data.SqlClient.SqlCommand(sql)) > 0;
        hddAD = null;
        return ret;
    }
    private Int32 getRandomNumber(int minimum, int maximum)
    {
        try
        {
            if (maximum <= minimum) return 0;
            Random r = new Random();
            int ret = Convert.ToInt32(Math.Floor((maximum - minimum) * r.NextDouble() + minimum));
            r = null;
            return ret;
        }
        catch (Exception e)
        {
            return 0;
        }
    }
    private string GetCompanyName(string companyafrowid)
    {
        string result = "";
        try
        {
            if (HttpContext.Current.Session["servercon"] != null)
            {
                HDDatabase HDD = new HDDatabase(HttpContext.Current.Session["servercon"].ToString());
                result = HDD.GetColumnValue("select company_name from ngcompany where af_row_id = '"+companyafrowid+"'");
                
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : GetCompanyName :"+ex.Message);
        }
        return result;
    }

    ////private bool isBasedOnEmail()
    ////{
    ////    bool status = false;
    ////    HDDatabase HDD = new HDDatabase();
    ////    try
    ////    {
    ////        string sql = "select mem_value1 from sy_acr_mem where af_row_id = 'fb2a35dfafaf1323'";
    ////        string basedonemail= HDD.GetColumnValue(sql);
    ////        if(basedonemail.Trim()!="")
    ////        {
    ////            status = Convert.ToBoolean(basedonemail);
    ////        }

    ////    }
    ////    catch(Exception ex)
    ////    {
    ////        LogWriter.WriteLog("Error: isBasedOnEmail: "+ex.Message);
    ////    }
    ////    finally
    ////    {
    ////        HDD = null;
    ////    }
    ////    return status;
    ////}

    private string GetFromAddress(bool isBasedOnEmail)
    {
        string result = "";
        HDDatabase HDD = new HDDatabase();
        try
        {
            if (isBasedOnEmail)
            {
                if (Session["user_afrowid"] != null)
                {
                    string sql = "select email_id from sy_usr where af_row_id = '" + Session["user_afrowid"].ToString() + "'";

                    result = HDD.GetColumnValue(sql);

                }

            }
            else
            {
                if (Session["userid"] != null)
                {
                    string userid = Session["userid"].ToString();
                    if (userid != "")
                    {
                        if (validateRegEx(userid, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))
                        {
                            result = userid;
                        }
                        
                    }
                }
            }
        }
        catch
        {

        }
        finally
        {
            HDD = null;
        }
        return result;

    }

    private bool validateRegEx(string input, string exp)
    {
        try
        {
            bool ret = false;
            System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(exp);
            ret = re.IsMatch(input);
            re = null;
            return ret;
        }
        catch (Exception e)
        {
            return true;
        }
    }
    private string GetParamterBindValue(string strBindRowID, string searchtext)
    {
        BindControl BC = new BindControl();
        HDDatabase HDD = new HDDatabase();
        string result = "";
        try
        {
            //if (searchtext.Trim() != "")
            //{
                string sql = BC.GetSearchSQLBySearchValue(strBindRowID, searchtext, true, false,"");
                DataTable dt = HDD.GetDataTable(sql);
                if (dt != null)
                    if (dt.Rows.Count > 0)
                        result = dt.Rows[0]["val"].ToString();
            //}
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("SearchPopup : GetParameterBindValue :" + ex.Message);
        }
        finally
        {
            BC = null;
            HDD = null;
        }
        return result;
    }
    private void setPageTitle()
    {
        try
        {
            if (Session["pageTitle"] != null)
            {
                Page.Header.Title = Session["pageTitle"].ToString();
            }
            else
            {
                if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(".") + "\\maxbloxtitle.ini"))
                {
                    System.IO.StreamReader sr = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(".") + "\\maxbloxtitle.ini");
                    Session["pageTitle"] = sr.ReadLine();
                    Page.Header.Title = Session["pageTitle"].ToString();
                    sr.Close();
                    sr = null;
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in setPageTitle function. Error: " + e.Message);
        }
    }
}
